package com.myapp.myhome.activity;

import java.util.List;

import org.w3c.dom.Text;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.myapp.myhome.R;
import com.myapp.myhome.adapter.MySerchAdapter;
import com.myapp.myhome.slidelistview.SwipeMenu;
import com.myapp.myhome.slidelistview.SwipeMenuCreator;
import com.myapp.myhome.slidelistview.SwipeMenuItem;
import com.myapp.myhome.slidelistview.SwipeMenuListView;
import com.myapp.myhome.slidelistview.SwipeMenuListView.OnMenuItemClickListener;
import com.myapp.myhome.utils.AllUtils;
import com.myapp.myhome.utils.MainUtils;

public class SearchAllInfoActivity extends BaseActivity {

	private TextView title_text;
	private Button title_back;
	private Button search_btn_all;
	private SwipeMenuListView mListView;
	MainUtils mUtils;
	String str_date;
	MySerchAdapter adapter;
	List<AVObject> list;
	SwipeMenuItem payItem;

	// ---------------------------
	private PopupWindow popupWindow;
	private View popView;
	private View parent;
	private TextView popup_text_date;
	private TextView popup_text_money;
	private TextView popup_text_who;
	private TextView popup_text_yufu;
	private Button popup_btn_cancel;
	private Button popup_btn_sure;
	private ProgressBar popup_bar_wait;

	// ------------------------------

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_search_all);
		mUtils = new MainUtils(this);
		str_date = mUtils.getDate().substring(0, 7);
		initPopupWindows();
		init();
	}

	private void init() {
		title_text = (TextView) this.findViewById(R.id.titlebar_title);
		title_text.setText("本月支出记录");
		title_back = (Button) this.findViewById(R.id.titlebar_back);
		title_back.setVisibility(View.VISIBLE);
		title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		// --------------------------------------------------
		mListView = (SwipeMenuListView) this
				.findViewById(R.id.search_all_listview);
		setListView();
		adapter = new MySerchAdapter(this);
		mListView.setAdapter(adapter);
		getAllInfo();
		search_btn_all = (Button) this.findViewById(R.id.search_all_btn);
		search_btn_all.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 打算这边执行全部结算

			}
		});
	}

	View view_list_foot;

	// 设置listview的侧滑结算
	private void setListView() {
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				payItem = new SwipeMenuItem(SearchAllInfoActivity.this);
				// 0498d8 Color.rgb(0xFF, 0x72,0x56)
				payItem.setBackground(new ColorDrawable(Color.rgb(0x04, 0x98,
						0xd8)));
				// 设置宽度
				payItem.setWidth(dp2px(120));
				payItem.setTitle("结算");
				// set item title fontsize
				payItem.setTitleSize(18);
				// set item title font color
				payItem.setTitleColor(Color.WHITE);
				// 加入到item里面，不添加则不显示
				switch (menu.getViewType()) {
				case 0:
					menu.addMenuItem(payItem);
				case 1:
					break;
				}
			}

		};
		mListView.setMenuCreator(creator);
		// 接下来设置listview foot 点击加载更多

		view_list_foot = LayoutInflater.from(SearchAllInfoActivity.this)
				.inflate(R.layout.listview_foot_layout, null);
		mListView.addFooterView(view_list_foot);

		mListView.setOnScrollListener(new OnScrollListener() {
			private int lastItemIndex;// 当前ListView中最后一个Item的索引

			// 当ListView不在滚动，并且ListView的最后一项的索引等于adapter的项数减一时则自动加载（因为索引是从0开始的）
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
						&& lastItemIndex == adapter.getCount() - 1) {

					// 加载数据代码 这边去执行
					getOtherInfo();
				}
			}

			// 这三个int类型的参数可以自行Log打印一下就知道是什么意思了
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// ListView 的FooterView也会算到visibleItemCount中去，所以要再减去一
				lastItemIndex = firstVisibleItem + visibleItemCount - 1 - 1;
			}
		});

		// 设置点击时间
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu,
					int index) {
				// 这边执行结算-----------点击结算按钮后弹出对话框，然后确定结算

				showPopupWindow(position);
				return false;
			}
		});
	}

	int firstGet = 25;// 刚进入界面时加载的条数
	int nextGet = 10;// 接下来分页加载时加载的数据
	int index = 0;// 第几次加载

	// 刚开始进来的时候查找记录，最多查找30条，实际上记录太多估计要用到分页
	private void getAllInfo() {
		// 这边是获取本月的支出---因此需要获取本月的月份 类似这样---> 2015-08

		AVQuery<AVObject> query = new AVQuery<AVObject>("Expenses");
		// query.whereMatches("who", "庄宏展");
		query.whereMatches("date", str_date);// 这边将本月的传进去 2015-08
		query.orderByDescending("eid");
		query.setLimit(firstGet);// 设置首次查询最多显示30个
		query.findInBackground(new FindCallback<AVObject>() {
			public void done(List<AVObject> avObjects, AVException e) {
				if (e == null) {
					Log.d("成功", "查询到" + avObjects.size() + " 条符合条件的数据");
					list = avObjects;
					adapter.setData(list);
				} else {
					Log.d("失败", "查询失败");
					AllUtils.showToast(SearchAllInfoActivity.this, "查询错误");
				}
			}
		});
	}

	TextView foot_text;
	ProgressBar foot_bar;

	// 这边是在加载更多选项
	public void getOtherInfo() {
		foot_text = (TextView) view_list_foot.findViewById(R.id.list_foot_text);
		foot_bar = (ProgressBar) view_list_foot
				.findViewById(R.id.list_foot_bar);
		foot_text.setText("正在加载...");
		foot_text.setVisibility(View.VISIBLE);
		foot_bar.setVisibility(View.VISIBLE);

		AVQuery<AVObject> query = new AVQuery<AVObject>("Expenses");
		query.whereMatches("date", str_date);// 这边将本月的传进去 2015-08
		query.orderByDescending("eid");
		query.setLimit(nextGet);// 设置本次查询最多显示30个
		query.setSkip(firstGet + nextGet * index); // 忽略前几次的总个数
		query.findInBackground(new FindCallback<AVObject>() {
			public void done(List<AVObject> avObjects, AVException e) {

				if (e == null) {
					if (avObjects.size() != 0) {
						index++;
						list.addAll(avObjects);
						adapter.setData(list);
						foot_text.setText("加载更多");
						foot_bar.setVisibility(View.GONE);
					} else {
						foot_text.setText("没有更多数据了");
						foot_bar.setVisibility(View.GONE);
					}
				} else {
					Log.d("失败", "查询失败");
					AllUtils.showToast(SearchAllInfoActivity.this, "查询错误");
				}
			}
		});

	}

	private void initPopupWindows() {
		parent = findViewById(R.id.search_re);
		popView = getLayoutInflater().inflate(R.layout.popup_layout_jiesuan,
				null);
		popupWindow = new PopupWindow(popView,
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		// popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setOutsideTouchable(true);

		popup_text_date = (TextView) popView
				.findViewById(R.id.search_popup_text_date);
		popup_text_money = (TextView) popView
				.findViewById(R.id.search_popup_text_money);
		popup_text_who = (TextView) popView
				.findViewById(R.id.search_popup_text_who);
		popup_text_yufu = (TextView) popView
				.findViewById(R.id.search_popup_text_yufu);
		popup_btn_cancel = (Button) popView
				.findViewById(R.id.search_popup_btn_cancel);
		popup_btn_sure = (Button) popView
				.findViewById(R.id.search_popup_btn_sure);
		popup_bar_wait = (ProgressBar) popView
				.findViewById(R.id.search_popup_wait_bar);
		popup_btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				popupWindow.dismiss();
			}
		});

	}

	private void showPopupWindow(int position) {
		popupWindow.setAnimationStyle(R.style.search_popWindow_animation);
		// 点击弹出泡泡窗口
		popupWindow.showAtLocation(parent, Gravity.TOP, 0, 30);
		AVObject av = list.get(position);
		popup_text_date.setText(av.getString("date"));
		popup_text_money.setText(av.getString("money"));
		popup_text_who.setText(av.getString("who"));
		popup_text_yufu.setText(av.getString("whopay"));
		final String objectId = av.getObjectId();
		popup_btn_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 这边执行修改的操作
				popup_btn_cancel.setVisibility(View.VISIBLE);
				updateState(objectId);

			}
		});
	}

	// 更新结算--根据objectid去执行
	private void updateState(String objectId) {
		AVObject post = AVObject.createWithoutData("Expenses", objectId);
		// 更新属性
		post.put("paystate", true);
		// 保存
		post.saveInBackground(new SaveCallback() {

			@Override
			public void done(AVException arg0) {
				if (arg0 == null) {
					AllUtils.showToast(SearchAllInfoActivity.this, "结算成功");
					popup_btn_cancel.setVisibility(View.VISIBLE);
					popupWindow.dismiss();
					getAllInfo();
				} else {
					AllUtils.showToast(SearchAllInfoActivity.this, "结算失败,请重试");
					popup_btn_cancel.setVisibility(View.VISIBLE);

				}

			}
		});
	}

	public int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				this.getResources().getDisplayMetrics());
	}
}
